package vn.edu.ptithcm.pim.controller;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Company;
import vn.edu.ptithcm.pim.dom.User;
import vn.edu.ptithcm.pim.service.CompanyService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class CompanyController extends SimpleFormController {

	private CompanyService companyService;
	private UserService userService;
	private LocaleResolver localeResolver;

	public CompanyController() {
		super();
		setSessionForm(true);
		setCommandName("user");
		setCommandClass(User.class);
		setFormView(UrlConstants.COMPANY_URL);
		setSuccessView(UrlConstants.COMPANY_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return ParamUtil.getObject(request, "user", new User());
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		Map<String, Object> bean = new HashMap<String, Object>();
		String id = ParamUtil.getString(request, "id", "");
		bean.put("id", id);

		Company company = (Company) companyService.getAll().get(0);
		bean.put("company", company);

		if (userService.isSignedIn(request)) {
			bean.put("isSigned", true);
			String loginName = userService.getCurrentLogin(request);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put("user", userService.findByLoginName(loginName));
		} else {
			bean.put("isSigned", false);
		}

		String locale = ParamUtil.getString(request, "locale", "");
		if (!locale.isEmpty()) {
			getLocaleResolver()
					.setLocale(request, response, new Locale(locale));
		} else {
			locale = getLocaleResolver().resolveLocale(request).getLanguage();
		}
		request.setAttribute("locale", locale);
		request.setAttribute("bean", bean);
		return super.showForm(request, response, errors);
	}

	public LocaleResolver getLocaleResolver() {
		return localeResolver;
	}

	public void setLocaleResolver(LocaleResolver localeResolver) {
		this.localeResolver = localeResolver;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
